import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

interface UserState {
  token: string | null
  userInfo: {
    id: number
    username: string
    role: string
    point?: number
  } | null
}

interface LoginForm {
  username: string
  password: string
}

interface RegisterForm extends LoginForm {
  email: string
  verificationCode: string
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('token'),
    userInfo: null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.userInfo?.role === 'admin',
    userPoints: (state) => state.userInfo?.point || 0
  },
  
  actions: {
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },
    
    setUserInfo(userInfo: UserState['userInfo']) {
      this.userInfo = userInfo
    },
    
    async login(username: string, password: string) {
      console.log('store: 开始登录');
      try {
        const formData = new URLSearchParams()
        formData.append('username', username)
        formData.append('password', password)

        const result = await request('/user/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: formData
        })
        
        this.setToken(result.tokenValue)
        await this.fetchUserInfo()
        return true
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败')
        throw error
      }
    },

    async register(formData: RegisterForm) {
      try {
        const response = await request('/user/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: formData.username,
            password: formData.password,
            email: formData.email,
            code: formData.verificationCode,
            role: 0
          })
        })
        return true
      } catch (error: any) {
        ElMessage.error(error.message || '注册失败')
        throw error
      }
    },

    async sendVerificationCode(email: string) {
      try {
        const formData = new URLSearchParams()
        formData.append('email', email)
        
        await request('/user/sendCode', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: formData
        })
        
        ElMessage.success('验证码已发送到您的邮箱')
        return true
      } catch (error: any) {
        ElMessage.error(error.message || '验证码发送失败')
        throw error
      }
    },

    async fetchUserInfo() {
      try {
        const userInfo = await request('/user/getUserInfo')
        this.setUserInfo(userInfo)
      } catch (error: any) {
        ElMessage.error(error.message || '获取用户信息失败')
        throw error
      }
    },
    
    async signIn() {
      try {
        const result = await request('/signIn', {
          method: 'POST'
        })
        if (result.code === 0) {
          ElMessage.success('签到成功，获得积分！')
          await this.fetchUserInfo()
          return true
        }
        return false
      } catch (error: any) {
        ElMessage.error(error.message || '签到失败')
        throw error
      }
    },
    
    logout() {
      this.token = null
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      Object.keys(localStorage).forEach(key => {
        if (key.startsWith('user_') || key.startsWith('auth_')) {
          localStorage.removeItem(key)
        }
      })
    }
  }
})